/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package trace;

/**
 *
 * @author phil
 */
public class CorrelatedPredictor implements Runnable {
        private long M_BIT = 0x1fff;
        private int count = 0, misPrediction = 0;
        private int bits;
        private int h;
        private CBranch cbranchtable[];
        private Reader traceFile;
        private Writer outputFile;

        public CorrelatedPredictor(Reader iFile, Writer oFile, int h, int n){
            this.traceFile = iFile;
            this.outputFile = oFile;
            this.h = h;
            this.cbranchtable = new CBranch[(int) M_BIT + 1];
            this.bits = n;
        }

        public CorrelatedPredictor(Reader iFile, Writer oFile, int h, int n, int m){
            this.traceFile = iFile;
            this.outputFile = oFile;
            this.h = h;
            this.cbranchtable = new CBranch[(int) M_BIT + 1];
            this.bits = n;
            this.M_BIT = (1<<(m+1)) - 1;
        }


        public void run() {
            String traceStr;
            String[] fileOption = new String[2];
            traceStr = traceFile.readLine();
            int index,outcome;
            long address;
            String output;
            System.out.println("Starting correlating " + traceFile.filename + " " + bits);
            while((traceStr != null)){
                Reader.parseString(fileOption, traceStr);
                address = Long.parseLong(fileOption[0]);
                outcome = Integer.parseInt(fileOption[1]);
                index = (int) (address & M_BIT);
                if (cbranchtable[index] == null) {
                    cbranchtable[index] = new CBranch(h,bits);
                }
                int prediction = cbranchtable[index].updatePrediction(outcome);
                if (prediction != outcome) misPrediction++;
                count++;
                traceStr = traceFile.readLine();
            }
            System.out.println("Done running correlating " + traceFile.filename + " " + bits);
            this.summary();
            outputFile.close();
        }

         public void summary(){
            this.outputFile.writeToFile("Index,Misprediction,Count");
            int lcount = 1;
            for(int i=0;i<cbranchtable.length;i++){
                if(this.cbranchtable[i] != null){
                    lcount++;
                    this.outputFile.writeToFile(i + "," + this.cbranchtable[i].getMisPrediction() + "," + this.cbranchtable[i].getCount());
                }
            }
            this.outputFile.writeToFile("," + misPrediction + "," + count + "," + "=B"+(lcount+1)+"/C"+(lcount+1)+"*100");
        }
}
